package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.nhc.database.dbmodel.QiyaInfo;
import com.nhc.database.manager.QiyaCenter;
import com.nhc.model.TripDataFileHandle;
import com.nhc.model.TripDatainfo;
import com.nhc.model.TripItem;
import com.nhc.view.TripItemViewLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.TopMenuWindow;

//点选之前 累计爬升+海拔  （即时的）--可以换区
//点选后  显示选中时间的 气压+高度 -- 点击返回后返回默认区域

public class QiyaActivity extends BaseActivity implements TimeRefresher.OnTimeRefreshListener, View.OnClickListener {
    private final String TAG = "QiyaActivity";

    public static Intent createIntent(Context context) {
        return new Intent(context, QiyaActivity.class);
    }
    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qiya_activity);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
//        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        mTripDatainfo = TripDataFileHandle.getInstance().mTripDatainfo;
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private LineChartView ll_chart_0;

    private TripItemViewLayout qiyainfo[] = new TripItemViewLayout[2];
    private int[] LL_CTRL = {R.id.qiyainfo_0, R.id.qiyainfo_1};

    @Override
    public void initView() {//必须在onCreateView方法内调用
        for (int i = 0; i < LL_CTRL.length; i++) {
            qiyainfo[i] = (TripItemViewLayout) findViewById(LL_CTRL[i]);
        }

        ll_chart_0 = (LineChartView) findViewById(R.id.ll_chart_0);
        ll_chart_0.setVisibility(View.GONE);
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    private TripDatainfo mTripDatainfo;
    boolean _isQuerying = false;

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initData() {//必须在onCreateView方法内调用
        if (_isQuerying) {
            return;
        }

        if (_addIndex == 0) {
            clearData();
        }

        _isQuerying = true;

        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                setData();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        finishQuery();
                        _isQuerying = false;
                    }
                });
            }
        });
    }

    private void clearData() {
        _A = 0;
        _lasttime = 0;
        mTPIndex.clear();
        mAxisXValues.clear();
        mPointValues.clear();

        _up = 0;
        _maxH = -99999;
        j = 0;
    }

    private void finishQuery() {
        ll_chart_0.setVisibility(View.VISIBLE);

        for (int i = 0; i < LL_CTRL.length; i++) {
            int index = mTripDatainfo.DATATYPE_INDEXS_QIYA[i];
            if (index < 0 || index >= mTripDatainfo.DATATYPE_NAMES.length) {
                continue;
            }
            String name = mTripDatainfo.DATATYPE_NAMES[index];
            String CC[] = mTripDatainfo.getInfoForQiya(index);
            if (index == 31) {
                //累计爬升
                String UP[] = SysUtils.getInstance().getDistanceStr((int) _up);
                qiyainfo[i].bindView(new TripItem(getString(R.string.ljps), UP[0], UP[1]));
            } else if (index == 38) {
                //最高海拔
                if (-99999 == _maxH) {
                    qiyainfo[i].bindView(new TripItem(getString(R.string.zghb), "-----", "---"));
                } else {
                    String ALT[] = SysUtils.getInstance().getDistanceStr((int) _maxH);
                    qiyainfo[i].bindView(new TripItem(getString(R.string.zghb), ALT[0], ALT[1]));
                }
            } else if (index == 36) {
                //海拔
            } else {
                qiyainfo[i].bindView(new TripItem(name, CC[0], CC[1]));
            }
        }

        initLineChart();
    }

    @Override
    public void onClick(View v) {//直接调用不会显示v被点击效果
        for (int i = 0; i < LL_CTRL.length; i++) {
            if (v.getId() == LL_CTRL[i]) {
//                toActivity(ChangeDataTypeActivity.createIntent(this, mTripDatainfo.DATATYPE_INDEXS_QIYA[i]), i);
                break;
            }
        }
    }

    private void refreshData(QiyaInfo qInfo) {
        if (qInfo == null) {
            qiyainfo[0].bindView(new TripItem(getString(R.string.ljps), "-----", "---"));
            qiyainfo[1].bindView(new TripItem(getString(R.string.hb), "-----", "---"));
            return;
        }
        String UP[] = SysUtils.getInstance().getDistanceStr((int) qInfo.getUp());
        qiyainfo[0].bindView(new TripItem(getString(R.string.ljps), UP[0], UP[1]));
        String ALT[] = SysUtils.getInstance().getDistanceStr((int) qInfo.getAltitude());
        qiyainfo[1].bindView(new TripItem(getString(R.string.hb), ALT[0], ALT[1]));
    }

    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
    private List<Integer> mTPIndex = new ArrayList<Integer>();

    //    x时间-y海拔高度
    public String getTimeStr(long datetime) {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "M-dd HH:mm:ss");
        Date curDate = new Date(datetime);
        String res = formatter.format(curDate);
        return res;
    }

    ArrayList<QiyaInfo> qiyaInfoList;
    double _up = 0;//累计爬升
    double _maxH = -99999;//最高海拔
    int _addIndex = 0;//已加入的数据
    double _A = 0;
    long _lasttime = 0;
    int j = 0;

    private void setData() {
        QiyaCenter.getInstance().doQueryQiyaInfo();
        qiyaInfoList = QiyaCenter.getInstance().getQiyaInfoList();

        if (qiyaInfoList == null) {
            return;
        }
        //1分钟 插一个数据
        int size = qiyaInfoList.size();
        int i = _addIndex;
        for (i = _addIndex; i < size; i++) {
            QiyaInfo qInfo = qiyaInfoList.get(i);
            long thistime = qInfo.getDatetime();
            boolean needAdd = false;
            double B = qInfo.getAltitude();

            if (B > _maxH) {
                _maxH = B;
            }
            if (i > 0 && B > _A) {
                _up += B - _A;
                qInfo.setUp(_up);
            } else {
                needAdd = true;
            }
            _A = B;

            if (i == qiyaInfoList.size() - 1) {
                thistime = _lasttime + 60000;
            }

            if (thistime >= _lasttime + 60000) {
                needAdd = true;
            }

            if (needAdd) {
                //设置X 轴的显示
                String xName = getTimeStr(thistime);
                mAxisXValues.add(new AxisValue(j).setLabel(xName));
                //图表的每个点的显示
                mPointValues.add(new PointValue(j, (int) qInfo.getAltitude()));
                _lasttime = (thistime / 60000) * 60000;
                mTPIndex.add(j);
                j++;
            }
        }
        _addIndex = i;

    }

    //图表参数说明
    //htqInfo://blog.csdn.net/u013360656/article/details/52875230
//    htqInfo://www.jianshu.com/p/90a544b739b1
    private void initLineChart() {

        List<Line> lines = new ArrayList<Line>();
        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(false);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        lines.add(line);

        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.GRAY);  //设置字体颜色
        axisX.setName("时间-海拔");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(6); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setName(getString(R.string.hb));//y轴标注
        axisY.setTextSize(10);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //y轴设置在右边

        int size = mTPIndex.size();
        int maxZoom = 20;
        maxZoom = size / 3;
        if (maxZoom < 2) {
            maxZoom = 2;
        }

        //设置行为属性，支持缩放、滑动以及平移
        ll_chart_0.setInteractive(true);
        ll_chart_0.setZoomType(ZoomType.HORIZONTAL);
        ll_chart_0.setMaxZoom((float) maxZoom);//最大方法比例
        ll_chart_0.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        ll_chart_0.setLineChartData(data);
        ll_chart_0.setVisibility(View.VISIBLE);
        ll_chart_0.setOnValueTouchListener(new LineChartOnValueSelectListener() {

            @Override
            public void onValueDeselected() {
            }

            @Override
            public void onValueSelected(int lineIndex, int pointIndex, PointValue value) {
                if (pointIndex >= 0 && pointIndex < mTPIndex.size()) {
                    int index = mTPIndex.get(pointIndex);
                    refreshData(qiyaInfoList.get(index));
                }
            }
        });
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（htqInfo://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
//        这4句代码可以设置X轴数据的显示个数（x轴0-7个数据）。
//        1 当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。
//        2 当数据点个数大于（29）的时候。
//        2.1 若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
//        2.2 若设置axisX.setMaxLabelChars(int count)这句话,33个数据点测试，
//        2.2.1 若 axisX.setMaxLabelChars(10); 里面的10大于v.right= 7; 里面的7，则 刚开始X轴显示7条数据，然后缩放的时候X轴的个数会保证大于7小于10
//        2.2.2 若小于v.right= 7;中的7,反正我感觉是这两句都好像失效了的样子 - -! 若这儿不设置 v.right= 7; 这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差

        //初始显示0～4的数据
        Viewport v = new Viewport(ll_chart_0.getMaximumViewport());
        if (size > 4) {
            v.left = size - 5;
            v.right = size - 1;
        } else {
            v.left = 0;
            v.right = 4;
        }

        ll_chart_0.setCurrentViewport(v);
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用

        for (int i = 0; i < qiyainfo.length; i++) {
            qiyainfo[i].setOnClickListener(this);
        }

    }

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    @Override
    public void onForwardClick(View v) {
        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_qiya)), REQUEST_TO_TOP_MENU, false);
    }

    private final int REQUEST_TO_TOP_MENU = 30;
    private boolean isToStop = false;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }

        if (RESULT_OK == resultCode) {
            initData();
        } else {
            if (requestCode >= 0 && requestCode < 3) {
                mTripDatainfo.DATATYPE_INDEXS_QIYA[requestCode] = resultCode;
                initData();
                return;
            }
        }

        switch (requestCode) {
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            isToStop = false;
                            break;
//                        case 1:
//                            isToStop = true;
//                            break;
                        case 1:
                            QiyaCenter.getInstance().doDeleteAllQiyaInfo();
                            _addIndex = 0;
                            initData();
                            break;
                        case 2:
                            //校准气压计
                            toActivity(QiyaSetActivity.createIntent(this), 7);
                            break;
                        default:
                            break;
                    }
                }
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            default:
                break;
            case KeyEvent.KEYCODE_BACK:
                if (_isQuerying) {
                    return true;
                }
                break;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {
        if (!isToStop) {
            initData();
        }
    }

    @Override
    public void onTimerStop() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        QiyaCenter.getInstance().getQiyaInfoList().clear();//数据太多不易一直保存在内存里
    }

    @Override
    protected void onResume() {
        super.onResume();
        TimeRefresher.getInstance().addTimeRefreshListener(TAG
                , 600000, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

}
